//
//  WJSignatureFontsListViewController.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/27.
//

import UIKit

protocol WJSignatureFontsListViewControllerDelegate: AnyObject {
    func useFontSignature(_ controller: WJSignatureFontsListViewController, signatureImage: UIImage, title: String)
}

class WJSignatureFontsListViewController: WJBaseViewViewController {
    
    weak var delegate: WJSignatureFontsListViewControllerDelegate? = nil

    private var fontFiles: [WJFontFile] = []
    private var selectedFontFile: WJFontFile? = nil
    
    private var topView = WJFontListTopView()
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        let width = (view.bounds.width - 35) / 2
        let height = width + 40 // 图片高度+文字高度
        layout.itemSize = CGSize(width: width, height: height)
        layout.minimumInteritemSpacing = 11
        layout.minimumLineSpacing = 11
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .clear
        cv.register(WJSignatureFontCell.self, forCellWithReuseIdentifier: "WJSignatureFontCell")
        cv.dataSource = self
        cv.delegate = self
        cv.allowsSelection = true
        
        return cv
    }()
    
    private lazy var createButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Create", for: .normal)
        button.setTitleColor(UIColor(hex: "#FFFFFF"), for: .normal)
        button.backgroundColor = UIColor(hex: "#1F87F6")
        button.layer.cornerRadius = 22
        button.addTarget(self, action: #selector(createSignature), for: .touchUpInside)
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = "Font Sign"
        commonInitSubviews()
        loadFonts()
    }
    
    func commonInitSubviews() {
        view.addSubview(topView)
        view.addSubview(collectionView)
        view.addSubview(createButton)
        topView.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(20)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(102)
        }

        collectionView.snp.makeConstraints { make in
            make.top.equalTo(topView.snp.bottom).offset(10)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(createButton.snp.top).offset(-20)
        }
        
        // 创建按钮约束
        createButton.snp.makeConstraints { make in
            make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-20)
            make.leading.equalToSuperview().offset(50)
            make.trailing.equalToSuperview().offset(-50)
            make.height.equalTo(44)
        }
    }
    
    func loadFonts() {
        fontFiles = (try? WJFontFile.findAllTyped()) ?? []
        collectionView.reloadData()
    }
    
    @objc private func createSignature() {
        guard let fontFile = selectedFontFile else {
            return
        }
        guard let text = self.topView.textField.text,
              !text.isEmpty else {
            return
        }

        WJFontManager.shared.loadFontWithPreview(fontFile, previewText: text) { [weak self] fileInfo, error in
            guard let self = self else { return }
            guard let image = fileInfo?.thumbnail else { return }
            self.delegate?.useFontSignature(self, signatureImage: image, title: fileInfo?.fullName ?? "")
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.view.endEditing(true)
    }
}

// MARK: - 集合视图数据源和代理
extension WJSignatureFontsListViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return fontFiles.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WJSignatureFontCell", for: indexPath) as! WJSignatureFontCell
        cell.configure(with: fontFiles[indexPath.item])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.visibleCells.forEach { $0.isSelected = false }
        let cell = collectionView.cellForItem(at: indexPath)
        cell?.isSelected = true
        // 设置当前项为选中
        let fontFile = fontFiles[indexPath.item]
        self.selectedFontFile = fontFile
        self.view.endEditing(true)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
}
